﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Zinnia.Common.Untilty
{
    /// <summary>
    /// 单例
    /// </summary>
    public class Singleton
    {
        static Singleton()
        {
            allSingletons = new ConcurrentDictionary<Type, object>();
        }
        static readonly IDictionary<Type, object> allSingletons;
        /// <summary>类型实例存储字典.</summary>
        public static IDictionary<Type, object> AllSingletons => allSingletons;
    }
    /// <summary>
    ///单例存储
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <remarks>对象访问不是同步的.</remarks>
    public class Singleton<T> : Singleton
    {
        static T instance;
        /// <summary><see cref="T"/>的单一实现</summary>
        public static T Instance
        {
            get { return instance; }
            set
            {
                instance = value;
                AllSingletons[typeof(T)] = value;
            }
        }
    }

    /// <summary>
    /// 提供集合类型单一实例
    /// </summary>
    /// <typeparam name="T">提供集合类型实例存储.</typeparam>
    public class SingletonList<T> : Singleton<IList<T>>
    {
        static SingletonList()
        {
            Singleton<IList<T>>.Instance = new List<T>();
        }

        /// <summary>指定<see cref="Singleton{T}"/>集合类型的实例</summary>
        public new static IList<T> Instance => Singleton<IList<T>>.Instance;
    }

    /// <summary>
    /// 提供字典类型单例对象存储.
    /// </summary>
    /// <typeparam name="TKey">字典key.</typeparam>
    /// <typeparam name="TValue">字典Value.</typeparam>
    public class SingletonDictionary<TKey, TValue> : Singleton<IDictionary<TKey, TValue>>
    {
        static SingletonDictionary()
        {
            Singleton<ConcurrentDictionary<TKey, TValue>>.Instance = new ConcurrentDictionary<TKey, TValue>();
        }

        /// <summary>指定字典类型单一实例</summary>
        public new static IDictionary<TKey, TValue> Instance => Singleton<ConcurrentDictionary<TKey, TValue>>.Instance;
    }
}
